package com.huangzhao.gulimall.cart.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.huangzhao.gulimall.cart.exception.CartExceptionHandler;
import com.huangzhao.gulimall.cart.feign.ProductFeignService;
import com.huangzhao.gulimall.cart.interceptor.CartInterceptor;
import com.huangzhao.gulimall.cart.service.CartService;
import com.huangzhao.gulimall.cart.to.UserInfoTo;
import com.huangzhao.gulimall.cart.vo.CartItemVo;
import com.huangzhao.gulimall.cart.vo.CartVo;
import com.huangzhao.gulimall.cart.vo.SkuInfoVo;
import com.huangzhao.gulimall.common.utils.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import static com.huangzhao.gulimall.common.constant.CartConstant.CART_PREFIX;

@Log4j2
@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String productRedisValue = (String) cartOps.get(skuId.toString());
        // 如果没有就添加数据
        if (StrUtil.isEmpty(productRedisValue)) {
            CartItemVo cartItemVo = new CartItemVo();
            // 开启第一个异步任务
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                // 1.远程查询当前要添加的商品信息
                R productSkuInfo = productFeignService.getInfo(skuId);
                SkuInfoVo skuInfo = (SkuInfoVo) productSkuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setSkuId(skuId);
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, executor);
            // 开启第二个异步任务
            CompletableFuture<Void> getSkuAttrValuesFuture = CompletableFuture.runAsync(() -> {
                // 2.查询skuAttrValues组合信息
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            // 等待所有异步任务完成后购物信息保存到redis
            CompletableFuture.allOf(getSkuInfoFuture, getSkuAttrValuesFuture).get();
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;

            // 如果购物车中已有该商品，则修改其数量即可,更新保存到redis中
        } else {
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    /**
     * 获取购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(cartKey);
        return operation;
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        // 用户已登录OrderServiceImpl
        if (userInfoTo != null) {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            // 临时购物车的key
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 合并临时购物车数据
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (CollectionUtil.isNotEmpty(tempCartItems)) {
                // 临时购物车的数据进行合并
                tempCartItems.stream().forEach(obj -> {
                    try {
                        addToCart(obj.getSkuId(), obj.getCount());
                    } catch (ExecutionException | InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                clearCartInfo(tempCartKey);
            }
            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

            // 未登录
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 获取临时购物车内的所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    /**
     * 获取购物车里的数据
     *
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operation.values();
        if (CollectionUtil.isNotEmpty(values)) {
            return values.stream().map((obj) -> JSON.parseObject((String) obj, CartItemVo.class)).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public void clearCartInfo(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        //修改商品状态
        cartItem.setCheck(check == 1 ? true : false);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), redisValue);

    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), redisValue);
    }

    @Override
    public void deleteIdCartInfo(Integer skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        List<CartItemVo> cartItemVoList = new ArrayList<>();
        //获取当前用户登录的信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        //如果用户未登录直接返回null
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            //获取购物车项
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //获取所有的
            List<CartItemVo> cartItems = getCartItems(cartKey);
            if (cartItems == null) {
                throw new CartExceptionHandler();
            }
            //筛选出选中的
            cartItemVoList = cartItems.stream()
                    .filter(items -> items.getCheck())
                    .map(item -> {
                        //更新为最新的价格（查询数据库）
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    })
                    .collect(Collectors.toList());
        }

        return cartItemVoList;
    }
}
